package org.mspring.mlog.web.freemarker.directive;

import java.io.IOException;
import java.util.List;
import java.util.Map;

import org.mspring.mlog.ServiceFactory;
import org.mspring.mlog.entity.Attachment;
import org.mspring.platform.qiniu.QiniuImageStyleUtils;
import org.mspring.platform.web.freemarker.DirectiveUtils;
import org.mspring.platform.web.freemarker.directive.AbstractDirectiveModel;

import freemarker.core.Environment;
import freemarker.template.TemplateDirectiveBody;
import freemarker.template.TemplateException;
import freemarker.template.TemplateModel;

/**
 * 从文章对应的附件图片中抽取一张
 *
 * @author Gao Youbo
 * @since 2014年5月16日
 */
@SuppressWarnings({ "rawtypes", "unchecked" })
public class PostImageDirectiveModel extends AbstractDirectiveModel {

    @Override
    public void exec(Environment env, Map params, TemplateModel[] loopVars, TemplateDirectiveBody body) throws TemplateException, IOException {
        String url = null;
        long postId = DirectiveUtils.getLongValue("post", params);
        if (postId != 0) {
            List<Attachment> attachs = ServiceFactory.getPostAttachService().listByPost(postId);
            if (attachs != null && !attachs.isEmpty()) {
                url = attachs.get(0).getUrl();
                int width = DirectiveUtils.getIntValue("width", params, 0);
                int height = DirectiveUtils.getIntValue("height", params, 0);
                width = width < 0 ? 0 : width;
                height = height < 0 ? 0 : height;
                if (width != 0 && height != 0) {
                    url = QiniuImageStyleUtils.generateByImageView(url, width, height);
                }
            }
        }
        env.__setitem__("postImgUrl", url);
    }
}
